package com.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.beans.Calculate;
import com.beans.Staff;
import com.services.SelectService;

@WebServlet("/select")
public class SelectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SelectService select = new SelectService();
	
	public SelectServlet() {
		super();

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		if (method == null) {
			List<Staff> list = select.selectAll();
			request.setAttribute("list", list);
			String message = request.getParameter("message");
			if(message!=null) {
				request.setAttribute("message", message);
			}
			request.getRequestDispatcher("adminSelect.jsp").forward(request, response);

		} else {
			String staffSnoStr = request.getParameter("id");
			int staffSno = Integer.parseInt(staffSnoStr);
			List<Calculate> list = select.selectAll(staffSno);
			request.setAttribute("list", list);
			request.getRequestDispatcher("select.jsp").forward(request, response);
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		String staffSnoStr = request.getParameter("id");
		int staffSno = Integer.parseInt(staffSnoStr);
		String month = request.getParameter("month");
		Calculate cal = select.selectThis(month, staffSno);
		List<Calculate> list = new ArrayList<>();
		if (cal != null) {
			list.add(cal);
			request.setAttribute("list", list);
			request.getRequestDispatcher("select.jsp").forward(request, response);
		} else {
			String message = "<script type='text/javascript' >alert('Salary not recorded');</script>";
			request.setAttribute("message", message);
			String admin=request.getParameter("admin");
			if(admin==null) {
				request.getRequestDispatcher("staff.jsp").forward(request, response);
			}
			else
				response.sendRedirect("/salary_manage/select?message="+message);
			
		}
		
	}

}
